var serverConstants = require('../constants/serverConstants.js');
var rspHandler = require('ResponseHandler.js');
var inner = {
  request: function (url, method, success, data, ifMask, error) {
    if (ifMask) {
      wx.showLoading({
        title: '加载中',
      });
    }
    wx.request({
      url: serverConstants.serverHost + url,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': wx.getStorageSync("token")
      },
      success: function (res) {
        if (ifMask) {
          wx.hideLoading();
        }
        if (!error) {
          if (!rspHandler.handle(res.data.code)) {
            if (res.data.code == 0) {
              //TODO success
              success(res.data.result);
            } else {
              console.info(res);
              wx.showModal({
                title: '错误',
                content: '遇到点问题',
                showCancel: false
              });
            }
          }
        } else {
          if (res.data.code == 0) {
            //TODO success
            success(res.data.result);
          } else {
            error(res.data);
          }
        }
      },
      fail: function (res) {
        console.info(res);
        if (ifMask) {
          wx.hideLoading();
        }
        wx.showModal({
          title: '错误',
          content: '遇到点问题',
          showCancel: false
        });
      }
    });
  }
};
var httpClient = {
  post: function (url, data, success) {
    inner.request(url, "POST", success, data, true);
  },
  get: function (url, success, error) {
    inner.request(url, "GET", success, null, true, error);
  },
  postNoMask: function (url, data, success) {
    inner.request(url, "POST", success, data, false);
  },
  getNoMask: function (url, success) {
    inner.request(url, "GET", success, null, false);
  }
};
module.exports = {
  get: httpClient.get,
  post: httpClient.post,
  getNoMask: httpClient.getNoMask,
  postNoMask: httpClient.postNoMask
};